<?php
class controller_contact extends __registry_controller
{
    public $_ = array();
    public $_layout = NULL;
    
    public $_content_header = 'OPEN';
    public $_content_top = 'OPEN';
    
	public function __construct()
    {	
		parent::add_object(array(
			'handle_string',
            'handle_upload',
            'handle_paging',
			'model_contact',
            'handle_validate',
            'model_users',
            'model_categories',
            'model_language',
            'database_mysql',
            'handle_permission'
		));
        $this->_layout =NULL;
        
	}
	
	public function index_action()
	{	
        /********Kiem tra login******************/
        $check_permission = $this->per_check_permission(NULL,false, NULL);
        /********end******************************/
        $seo2 = isset($this->_seokey[2])?$this->_seokey[2]:null;
        $seo3 = isset($this->_seokey[3])?$this->_seokey[3]:null;
		$enseo = end($this->_seokey);
        if(empty($seo2) || ($seo2==$enseo && intval($enseo)!=0) )
        {
            $html = $this->list_action();
        }
        elseif(!empty($seo3) && $seo3 == 'them-moi'){
            $html = $this->edit_action();
        }else{
            $html = $this->list_action();
        }
		return $html;
	}
    
    public function view_detail(){
        /**********************************************/
        
        $contact_alias = $this->_seokey[2];
        
        $html = $this->view->view_display('view_detail');
        $arrHtml = $this->view->view_get_block_html($html);
        
        $list_lang = $this->mdl_lang_list();
        $tabLangHtmlTitle = '';
        $tabLangDetail = '';
        $button_list = '';
        if(!empty($list_lang)){
            foreach($list_lang as $lang){
                $tabLangHtmlTitle .= $this->view->view_assign($arrHtml['tab_title'],array(
                                                                            'lang_name'                 => $lang['lang_name'],
                                                                            'lang_id'                    => $lang['lang_id']
                                                                        ));
                $contact_detail = $this->mdi_contact_detail($contact_alias, $lang['lang_id']);
                
                
                if(empty($contact_detail)){
                    $tabLangDetail .= $this->view->view_assign($arrHtml['tab_detail'],array(
                                                                            'FullContents'                 => $this->_['content_is_update'],
                                                                            'lang_id'                      => $lang['lang_id']
                                                                        ));
                }else{
                    $tabLangDetail .= $this->view->view_assign($arrHtml['tab_detail'],array(
                                                                            'FullContents'                 => $contact_detail['FullContents'],
                                                                            'lang_id'                      => $lang['lang_id']
                                                                        ));
                    $this->catID = $contact_detail['CatID'];
                }
                
            }    
            
        }
        $catId = $this->mdi_get_cat_cid($contact_alias);
        $this->_['url_add'] = URL_BASE . 'admin/quan-ly-gioi-thieu/chinh-sua/' . $catId['CatID'];
        
        
        
        $shtml = $this->view->view_assign_block($html,array('htmlTabTitleList'=>$tabLangHtmlTitle,
                                                            'htmlTabDetailList'=>$tabLangDetail));
		return $shtml;
    }
    
    public function edit_action()
	{
	   /* Check permission */
	   $this->per_check_permission();
			
	   $str_option_com = NULL;
       $this->_['sms'] = '';
       $this->_['dis_none'] = '';
       

       $catid = isset($this->_seokey[3])?intval($this->_seokey[3]):null;
       if($catid)
       {

           /* LAY DU LIEU CAT CUR */
           $cat_rows = $this->mdc_get_cat($catid);
           
           /*Khởi tạo cho cat 2 public*/
           if($catid == 2)
           { 
             $this->_['dis_none'] = ' style="display:none;" ';
             $_POST['SeoKey'][0] = 'home';
             $_POST['PID'] = 'home';
           }
           
           /* LAY DANH SACH NGON NGU */
           $arr_row_titles = $this->mdl_lang_list(); /* lang max */
           $alang = array(); /* lang data change not empty */
           $arr_lang_insert = array(); /* lang data ok insert */
           
           /* Kiểm tra lang có dữ liệu */
           if(!empty($_POST['CatName']) && !empty($arr_row_titles))
           {   
               foreach($arr_row_titles as $arr_row)
               {
                    $langid = $arr_row['lang_id'];
                    
                    if(!(
                        empty($_POST['CatName'][$langid])      &&
                        empty($_POST['SeoKey'][$langid])       &&
                        empty($_POST['Title'][$langid])        &&
                        empty($_POST['Desc'][$langid])         &&
                        empty($_POST['Keyword'][$langid])      &&
                        empty($_POST['TitleH1'][$langid])      &&
                        empty($_POST['TitleH2'][$langid])      &&
                        empty($_POST['DescF'][$langid])
                    )){
                        $alang[] = $langid;    
                    }
                    
               }
           }
           /*Kiểm tra lỗi lang có dữ liệu */
    	   if( !empty($_POST['PID']) && !empty($_POST['CatName']) && !empty($_POST['SeoKey']) )
           {
               $add = 0;
               if(!empty($alang)){
                   foreach($alang as $lang_id)
                   {    
                        if($catid == 2)
                        { 
                             $_POST['SeoKey'][$lang_id] = 'home-'.$lang_id;
                        }
                       $_POST['SeoKey'][$lang_id] = $this->str_seokey($_POST['SeoKey'][$lang_id]);
                        $seo_key = $this->mdc_get_seo_key($_POST['SeoKey'][$lang_id],$lang_id,$cat_rows['ID']);
                        if($seo_key>0)
                        {
                            $this->_['sms'] = $this->_['check_seo_key'].' '.$arr_row['lang_name'];
                            
                        }else if(empty($_POST['CatName'][$lang_id]))
                        {
                             $this->_['sms'] = $this->_['empty_cat_name'];  
                             
                        }else if(empty($_POST['SeoKey'][$lang_id]))
                        {
                        
                            $this->_['sms'] = $this->_['empty_seo_key'];
                                
                        }else{
                            /* Upload pic */
                            if(isset($_FILES['Img']) && !empty($_FILES['Img']['name']))
                            {
                                $img = $this->upload_img($_FILES['Img'],PATH_BASE.'/upload/images/categories/',time());
                                if($img)
                                {
                                    $_POST['Img'] = $img;
                                }
                                else{
                                    $this->_['sms'] = '';
                                }
                            }
                            $arr_lang_insert[] = $lang_id;
                        }   
                   }
                   
               }       
           }
           /**************save contact detail-phung*************************/
           if(!empty($alang)){
                foreach($alang as $lang){
                    $data_contact = array();
                    $data_contact['UserID'] = $_SESSION['ID'];
                    $data_contact['CID'] = 163;
                    $data_contact['NoIndexFollow'] = 1;
                    $data_contact['PostDate'] = date('Y-m-d');
                    
                    $data_contact_lang = array();
                    $data_contact_lang['LangID'] = $lang;
                    $data_contact_lang['FullContents'] = $_POST['FullContents'][$lang];
                     
                    $check_contact_lang_exit = $this->mdct_contact_lang_exit($catid,$lang);
                    $check_contact_exit = $this->mdct_contact_exit($catid,$lang);
                    if(empty($check_contact_exit)){
                        
                        $data_contact['ID'] = $catid;
                        $this->mdct_contact_insert('contact', $data_contact);
                    }else{
                        $this->mdct_contact_update('contact', $data_contact, 'ID='.$catid);
                    }
                    if(empty($check_contact_lang_exit)){
                        $data_contact_lang['ContactID'] = $catid;
                        $this->mdct_contact_insert('contact_lang', $data_contact_lang);
                    }else{
                        $this->mdct_contact_update('contact_lang', $data_contact_lang, 'ContactID='.$catid . ' AND LangID =' . $lang);
                    }
                    
                }
           }
            
           /* Lưu những lang đã kiểm tra */
            if(!empty($arr_lang_insert))
            {
                $add = 0;
                $id = 0;
                $done_ok = true;
                foreach($arr_lang_insert as $lagid)
                {
                    if($add==0)
                    {
                       $rs = $this->mdc_cat_update($cat_rows['ID']);
                       $add++;
                       if(!$rs)
                       {
                            $done_ok = false;
                       }
                    }
                    
                    if($rs!=0 && $done_ok == true)
                    {
                        $done = $this->mdc_cat_update_lang($cat_rows['ID'],$lang_id);
                        
                        if($done == false)
                        {
                            $done_ok = false;
                        }
                    }
               }
               
               /* Điều hướng khi tất cả đều thành công */
               if($done_ok==true)
               {
                    $this->request->rq_goto_window_parent(URL_BASE.$this->_seokey[0].'/'.$this->_seokey[1]);    
               }
                     
           }

           if(!empty($cat_rows['Img']))
           {
               $this->_['path_file_Img'] = urlencode($cat_rows['Img']);
               $this->_['file_Img'] = URL_BASE.'upload/images/categories/'.$cat_rows['Img'];
               $this->_['CatID'] = $cat_rows['ID'];
               $this->_['dis_none_input'] = 'display:none;';

           }else{

               $this->_['file_Img'] = URL_BASE.'upload/noimg.png';
               $this->_['dis_none_but'] = 'display:none;';
           }
           $this->_['title_editor'] = $this->_['title_editor_edit'];
           $this->_['val_order'] = isset($_POST['Order'])?$_POST['Order']:$cat_rows['Order'];
           $this->_['checked_horizontal'] = isset($_POST['HorizontalMenu'])&&$_POST['HorizontalMenu']==1?'checked="true"':($cat_rows['HorizontalMenu']==1?'checked="true"':null);
           $this->_['checked_vertical'] = isset($_POST['VerticalMenu'])&&$_POST['VerticalMenu']==1?'checked="true"':($cat_rows['VerticalMenu']==1?'checked="true"':null);
           
           if(!empty($arr_row_titles))
           {
               foreach($arr_row_titles as $arr_row)
               {    
                    $lang_id = $arr_row['lang_id'];
                    $cat_lang_row = $this->mdc_get_cat_lang($catid,$lang_id);
                    
                    $this->_['CatName_'.$lang_id] = isset($_POST['CatName'][$lang_id])?$_POST['CatName'][$lang_id]:$cat_lang_row['CatName'];
                    $this->_['SeoKey_'.$lang_id] = isset($_POST['SeoKey'][$lang_id])?$_POST['SeoKey'][$lang_id]:$cat_lang_row['SeoKey'];
                    $this->_['xTitle_'.$lang_id] = isset($_POST['Title'][$lang_id])?$_POST['Title'][$lang_id]:$cat_lang_row['Title'];
                    $this->_['Desc_'.$lang_id] = isset($_POST['Desc'][$lang_id])?$_POST['Desc'][$lang_id]:$cat_lang_row['Desc'];
                    $this->_['Keyword_'.$lang_id] = isset($_POST['Keyword'][$lang_id])?$_POST['Keyword'][$lang_id]:$cat_lang_row['Keyword'];
                    $this->_['TitleH1_'.$lang_id] = isset($_POST['TitleH1'][$lang_id])?$_POST['TitleH1'][$lang_id]:$cat_lang_row['TitleH1'];
                    $this->_['TitleH2_'.$lang_id] = isset($_POST['TitleH2'][$lang_id])?$_POST['TitleH2'][$lang_id]:$cat_lang_row['TitleH2'];
                    $this->_['DescF_'.$lang_id] = isset($_POST['DescF'][$lang_id])?$_POST['DescF'][$lang_id]:$cat_lang_row['DescF'];
               
                    $this->_['selected_show_'.$lang_id]= isset($_POST['Status'][$lang_id]) && $_POST['Status'][$lang_id]=='show'?'selected="true"':($cat_lang_row['Status']=='show'?'selected="true"':NULL);
                    $this->_['selected_hide_'.$lang_id]= isset($_POST['Status'][$lang_id]) && $_POST['Status'][$lang_id]=='hide'?'selected="true"':($cat_lang_row['Status']=='hide'?'selected="true"':NULL);
                    $this->_['selected_del_'.$lang_id]= isset($_POST['Status'][$lang_id]) && $_POST['Status'][$lang_id]=='del'?'selected="true"':($cat_lang_row['Status']=='del'?'selected="true"':NULL);
                    
                    /*****************show contact***********************/
                    $contact_detail = $this->mdct_contact_detail_edit($catid, $lang_id);
                    if(!empty($contact_detail)){
                        $this->_['FullContents_'.$lang_id] = isset($_POST['FullContents_'][$lang_id])?$_POST['FullContents_'][$lang_id]:$contact_detail['FullContents'];
                    }else{
                        $this->_['FullContents_'.$lang_id] = isset($_POST['FullContents_'][$lang_id])?$_POST['FullContents_'][$lang_id]:'';
                    }
               }
           }

    	   
           $this->_layout ='iframe';
           $noid = isset($this->_seokey[2])?intval($this->_seokey[2]):0;
           $resultHtml = '';
           $resultHtmlx = '';
           $resultTile ='';
           
           $html = $this->view->view_display("editor");
           /* Name Block HTML*/
           $this->arrBlockEditor = $this->view->view_get_block_html($html);
           $tabs_title = isset($this->arrBlockEditor['tabs_title'])?$this->arrBlockEditor['tabs_title']:Null;
           $tabs_title_ul = isset($this->arrBlockEditor['tabs_title_ul'])?$this->arrBlockEditor['tabs_title_ul']:Null;   
           $tabs_contents = isset($this->arrBlockEditor['tabs_contents'])?$this->arrBlockEditor['tabs_contents']:Null;
           $select_option_com = isset($this->arrBlockEditor['select_option'])?$this->arrBlockEditor['select_option']:Null;

           /* SELECT BOX CAT */
           $PID = isset($_POST['PID'])?$_POST['PID']:$cat_rows['PID'];
           $this->_['option_cat'] = $this->cat_list_box(0,0,$noid,$PID);
           
           /* SELECT BOX COM */
           $Com = isset($_POST['Com'])?$_POST['Com']:$cat_rows['Com'];
           $arr_com = $this->mdc_cat_com_box();
           if(!empty($arr_com))
           {
               foreach($arr_com as $row_com)
               { 
                    if($Com== $row_com['com_value'])
                    {
                        $row_com['selected'] = 'selected="true"';
                    }
                    else{
                        
                        $row_com['selected'] = '';
                    }
                    $str_option_com .= $this->view->view_assign($select_option_com,$row_com);
               }
               
               $this->_['option_com'] = $str_option_com;
           }
           
           
           /* TAO TAB TITLE */
           if(!empty($arr_row_titles)){
               foreach($arr_row_titles as $arr_row_title)
               {
                    $resultTile .= $this->view->view_assign($tabs_title,$arr_row_title);
               }
           } 
           $resultHtml .= $this->view->view_assign($tabs_title_ul,array('tabs_li'=>$resultTile));
           /* TAO NOI DUNG TAB */
           if(!empty($arr_row_titles))
           {
               foreach($arr_row_titles as $arr_row_title)
               {
                    $resultHtmlx .= $this->view->view_assign($tabs_contents,$arr_row_title);
               }
           }
           $resultHtml .= $resultHtmlx;
           
           
           /* CHEN MANG NGON NGU DE TAO HTML */
           $result =  $this->view->view_assign($resultHtml,$this->_);
    	   $strhtml = $this->view->view_assign_block($html,array('htmlCat'=>$result)); 
       }    
       return $strhtml;
	}
    
    private function cat_list_box($id,$indent,$noid=0,$select)
    {
        $indent +=1;
        $str ='';
        $rr = $this->mdc_cat_list_box($id,$noid);
        
        if(!empty($rr))
        {
            foreach($rr as $key=>$row)
            {
                                
                $arr_row = array(
                    'selected'=>($select==$row['ID']?'selected="true"':NULL),
                    'com_value' => $row['ID'],
                    'com_text' => str_repeat("&nbsp;&nbsp;", $indent).$row['CatName']
                );
                
                $str .= $this->view->view_assign($this->arrBlockEditor['select_option'],$arr_row);
                
                if( isset($row['ID']) && $str )
                {
                    $str .= $this->cat_list_box($row['ID'],$indent,$noid,$select);
                }
                
            }
            
        }
        
        return $str;
    }
    
    public function list_action(){

		/* Check permission */
		$this->per_check_permission();
		
        $limit = 15;
        $res_html = NULL;
        $seo2 = isset($this->_seokey[2])?$this->_seokey[2]:null;
		$enseo = end($this->_seokey);
        
        /********su ly phan chinh sua***************/
        if($seo2 == NULL){
            $this->request->rq_goto_window_parent(URL_BASE.$this->_seokey[0].'/');
        }
        $CatItem = $this->mdct_get_cat_cid($seo2);
        if(empty($CatItem)){
            $this->request->rq_goto_window_parent(URL_BASE.$this->_seokey[0].'/');
        }
        $this->_['CatName'] = $CatItem['CatName'];
        $CatID = $CatItem['CatID'];
        $this->_['url_edit'] = URL_BASE.'admin/'.$this->_seokey[1].'/'.$this->route->rt_get_seokey_act('edit').'/'.$CatID;

        $row = $this->mdct_get_list_contact($CatID);
        $html = $this->view->view_display('index');
        $arr_block_html = $this->view->view_get_block_html($html);
        
        $current = end($this->_seokey)?intval(end($this->_seokey)):1;
        $total = $this->mdct_contact_total_list($CatID);
        $url = !empty($cid)?URL_BASE.$this->_seokey[0].'/'.$this->_seokey[1].'/'.$seo2:URL_BASE.$this->_seokey[0].'/'.$this->_seokey[1];
        $this->_['paging'] = $this->paging_display($total, $current, $limit, $url, $this->_);
        
        $rows = $this->mdct_contact_list($CatID,$current,$limit);
        if(!empty($rows))
            foreach($rows as $row)
            {
                $row['url_item'] = URL_BASE.'admin/'.$this->_seokey[1].'/'.$this->route->rt_get_seokey_act('detail').'/'.$row['ID'];
                $res_html .= $this->view->view_assign($arr_block_html['contact'],$row);  
                
            }

        $shtml = $this->view->view_assign_block($html,array('htmlcontact'=>$res_html));
        
		return $shtml;
    }
    
    public function index_ajax_action()
	{
		/* Check permission */
		$this->per_check_permission();
        
        $this->_layout ='NO_LAYOUT';

        $active = isset($this->_seokey[3])?$this->_seokey[3]:null;
        $str_id = isset($this->_seokey[4])?$this->_seokey[4]:null;
        $str_path = isset($this->_seokey[5])?$this->_seokey[5]:null;

        if($active=='delpic' && !empty($str_path))
        {
            $this->mda_art_del_pic($str_id);
            unlink(PATH_BASE.'upload/images/categories/'.$str_path);
        }

        $done = $this->mdct_tool_func($this->model,$active,$str_id);
        if($done){
            return 'ok';
        }else{
            return 'noOk';
        }        
        
	}
    
    public function detail_action(){
        
		/* Check permission */
		$this->per_check_permission();
		
		$seo2 = isset($this->_seokey[3])?$this->_seokey[3]:null;
        $this->_layout = 'iframe';
        if($seo2 == NULL){
            $this->request->rq_goto_window_parent(URL_BASE.$this->_seokey[0].'/');
        }
        $this->_['id'] = $seo2;
        $item = $this->mdct_get_contact($seo2);
        $html = $this->view->view_display('detail');
        $html = $this->view->view_assign($html, $item);

        return $html;
    }
		
}